package com.example.oop.Service;

import com.example.oop.POJO.User;
import com.example.oop.Repository.RepositoryManager;
import com.example.oop.Repository.UserRepository;
import com.example.oop.Utils.Response;
import org.json.JSONObject;

public class RegisterService {
    private final UserRepository userRepository;

    public RegisterService() {
        this.userRepository = RepositoryManager.userRepository;
    }

    //    实现登陆操作
    public synchronized JSONObject doRegister(JSONObject registerRequest) {
        synchronized (RepositoryManager.userRepository) {
            JSONObject response;  //定义用来响应的JSON

            String username = registerRequest.optString("username", "");  //获取用户名
            String password = registerRequest.optString("password", "");  //获取密码
            String confirmPassword = registerRequest.optString("confirmPassword", "");  //获取确认密码

            User user = null;  //根据用户名获取用户信息
            if (userRepository.findByUsername(username).isPresent()) {
                user = userRepository.findByUsername(username).get();  //从数据库中获取用户
            }

            if (username.equals("")) {
                response = Response.getJsonObject("-1", "用户名不能为空！");
            } else if (password.equals("")) {
                response = Response.getJsonObject("-2", "密码不能为空！");
            } else if (confirmPassword.equals("")) {
                response = Response.getJsonObject("-3", "确认密码不能为空！");
            } else if (!password.equals(confirmPassword)) {
//            用户不存在并且两次输入密码不同
                response = Response.getJsonObject("-4", "您输入的两次密码不一致！");
            } else if (user != null) {  //用户是否存在
//            若用户存在
                response = Response.getJsonObject("-5", "该用户名已存在！");
            } else {
//            用户不存在,且密码无误
                user = new User(0, username, password);  //id采用自增长
                userRepository.save(user);
                response = Response.getJsonObject("0", "用户注册成功！");
            }

            return response;
        }
    }
}
